package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"oct30-hw/cache"
	"oct30-hw/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var list []models.Article
	redis_key := "article_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": list,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	redis_key := "article_detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var count int64
	models.DB.Model(&models.Article{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"data":  article,
		"count": count,
	})
}
func Like(c *gin.Context) {
	userID, _ := strconv.Atoi(c.PostForm("userID"))
	articleID, _ := strconv.Atoi(c.PostForm("articleID"))
	data := models.Like{
		Uid: userID,
		Ain: articleID,
	}
	tx := models.DB.Begin()
	err := tx.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	}
	var article models.Article
	err = tx.Where("id = ?", userID).First(&article).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据更新失败",
		})
		return
	}
	article.LikeCount++
	tx.Save(&article)
	tx.Commit()
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "点赞成功",
	})
}
